package com.example.util;

public class BytesUtils {
	
	
	private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', 
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    /**
     * 方法一：
     * byte[] to hex string
     * 
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }
            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }
        return new String(buf);
    }
    
    
    public static byte[] hexStringToBytes(String hexString){
    	if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
	
    private static byte charToByte(char c) {
        //return (byte) "0123456789ABCDEF".indexOf(c);
    	if(c>=0x30 && c<=0x39){
    		return (byte) (c - 0x30);
    	}else if(c>=0x41 && c<=0x46){
    		return (byte) (c - 0x37);
    	}else if(c>=0x61 && c<=0x66){
    		return (byte) (c - 0x57);
    	}
    	return 0;
    }


	public static byte[] intToBytes(int intValue, int length) {
		byte [] buff = new byte[length];
		
		int index = 0;
		for(int i=0;i<length;i++){
			byte byteValue =  (byte)( ((byte)(intValue>>index)) & 0xFF);
			buff[length-i-1] = byteValue; 
			index = index + 8;
		}
		
		
		return buff;
	}
	
}
